﻿using Entitas;

public sealed class TickSystem : IInitializeSystem, IExecuteSystem, ITearDownSystem
{
    private ITimeService _timeService;
    private Systems _logicSystems;

    public TickSystem(ITimeService timeService, Systems logicSystems)
    {
        _logicSystems = logicSystems;
        _timeService = timeService;
    }

    public void Initialize()
    {
        Contexts.sharedInstance.game.SetTick(1.0f / GameDefine.LOGIC_FPS, 0, 0);
        _logicSystems.Initialize();
    }

    public void Execute()
    {
        TickComponent tick = Contexts.sharedInstance.game.tick;
        float totalTickTime = tick.totalTickTime;
        totalTickTime += _timeService.GetDeltaTime();
        float tickTime = Contexts.sharedInstance.game.tick.tickTime;
        while (totalTickTime >= tickTime * tick.currentTick)
        {
            _logicSystems.Execute();
            _logicSystems.Cleanup();
            Contexts.sharedInstance.game.tick.currentTick++;
        }

        tick.totalTickTime = totalTickTime;
    }

    public void TearDown()
    {
        _logicSystems.TearDown();
    }
}